<?php
class FavoritesController extends AppController{
	public $uses = array("User","Tweet","Favorite","Follow");
	public  function index(){

	}

	public function beforeFilter() {
		parent::beforeFilter();
		$mobile = preg_match('/android/i',$_SERVER['HTTP_USER_AGENT']);
		//debug($_SERVER['HTTP_USER_AGENT']);
		//debug($mobile);
		if($mobile){
			$this->autoRender =false;
		}
		else{
			$this->autoRender = true;
		}
	}
	/**
	 * this make a favorite for a tweet
	 * @userid id of user who like the tweet
	 * @tweetid id of tweet that user like this
	 */
	public function favorite(){
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty($this->request->data["userid"]) || empty($this->request->data["tweetid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$userid = $this->request->data["userid"];
				$tweetid = $this->request->data["tweetid"];
				$favorited = $this->Favorite->findByUserIdAndTweetId($userid,$tweetid);
				if($favorited){
					$data = array("status_code" => -1 , "message" => "favorited cannot hit again","entity" => $favorited);
					return json_encode($data);
				}else{
					$this->Favorite->create();
					$this->Favorite->set(array("user_id" => $userid, "tweet_id" => $tweetid));
					$this->Favorite->save();
					$data = array("status_code" => 0 , "message" => "Sucess favorite","entity" => array());
					return json_encode($data);
				}
			}
		}else{
			$this->autoRender = true;
		}
	}


	/**
	 * this make a unfavorite for a tweet
	 * @userid id of user who want to unlike the tweet
	 * @tweetid id of tweet that user unlike this
	 */
	public function unfavorite(){
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty($this->request->data["userid"]) || empty($this->request->data["tweetid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$userid = $this->request->data["userid"];
				$tweetid = $this->request->data["tweetid"];

				$favorited = $this->Favorite->findByUserIdAndTweetId($userid,$tweetid);
				if(!$favorited){
					$data = array("status_code" => -1 , "message" => "unfavorited not exist","entity" => array());
					return json_encode($data);
				}else{
					$this->Favorite->deleteAll(array("Favorite.user_id" => $userid, "Favorite.tweet_id" => $tweetid),false);
					$data = array("status_code" => 0 , "message" => "Sucess unfavorite","entity" => $favorited);
					return json_encode($data);
				}
			}
		}else{
			$this->autoRender = true;
		}
	}


	/**
	 * this make a unfavorite for a tweet
	 * @userid id of user who want to unlike the tweet
	 * @tweetid id of tweet that user unlike this
	 */
	public function favorite_count(){
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty($this->request->data["get_userid"]) || empty($this->request->data["tweetid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				return json_encode($data);
			}else{
				$userid = $this->request->data["get_userid"];
				$tweetid = $this->request->data["tweetid"];

				$favoriteds = $this->Favorite->find("count",array("conditions" =>
						array("Favorite.tweet_id" => $tweetid)) );

				$data = array("status_code" => 0 , "message" => "","entity" => $favoriteds);
				return json_encode($data);

			}
		}else{
			$this->autoRender = true;
		}
	}
	
	public function favorite_list(){
		if($this->request->is("post")){
			$this->autoRender = false;
			if(empty($this->request->data["get_userid"]) || empty($this->request->data["tweetid"])){
				$data = array("status_code" => -1 , "message" => "access denied","entity" => array());
				echo json_encode($data);
			}else{
				$userid = $this->request->data["get_userid"];
				$currentuserid = $this->request->data["userid"];
				$tweetid = $this->request->data["tweetid"];
				
				$this->Favorite->unbindModel(array("belongsTo" => array("Tweet")));
				$favoriteds = $this->Favorite->find("all",array("conditions" =>
						array("Favorite.tweet_id" => $tweetid),"fields" => array("User.id","User.username","User.email","User.avatar","User.screen_name")) );
				$favoriteds = $this->checkFollowerStatus($currentuserid, $favoriteds);
				$data = array("status_code" => 0 , "message" => "","entity" => $favoriteds);
				echo json_encode($data);
			}
		}else{
			$this->autoRender = true;
		}
	}
	
	private  function checkFollowerStatus($userid,$favorites){
		$followings = $this->Follow->find("all" , array("conditions" => array("follower_id" => $userid),
				"fields" => array("FollowerUser.id"),"order" => array('id' => 'asc')));
		
		for($i = 0;$i < count($favorites);$i++){
			for($j = 0;$j < count($followings) ; $j++){
				if($favorites[$i]["User"]["id"] == $followings[$j]["FollowerUser"]["id"]){
					$favorites[$i]["User"]["followStatus"] = true;
					break;
				}
			}
			if(!isset($favorites[$i]["User"]["followStatus"])){
				$favorites[$i]["User"]["followStatus"] = false;
			}
		}
		return  $favorites;
	}
	public function get_favorite_tweet(){
		//$this->autoRender=false;
		$err = null;
		$response;
		if($this->request->is('post')){
			if(empty($this->request->data['user_id'])){
				$err .= "not found tweet_id param";
				 
			}
			if(empty($this->request->data['count'])){
				$err .= "not found count param";
					
			}
			if(empty($this->request->data['page'])){
				$err .= "not found page param";
					
			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				 
				$userId = $this->request->data['user_id'];
				$count = $this->request->data['count'];
				$page = $this->request->data['page'];
				if($page<1)$page = 1;
				$page = ($page-1)*$count;
				$query =  "select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime , 1 as favorite ,not isnull(RTByme.id) as retweetedbyme,Retweet.*,
				ParentUser.id ,ParentUser.avatar,ParentUser.username,ParentUser.email,ParentUser.screen_name,ParentUser.created
				from favorites as Favorite
				inner join tweets as Tweet
				on Favorite.user_id = $userId and
				Favorite.tweet_id = Tweet.id
				inner join users as User
				on User.id = Tweet.user_id
				left join tweets as Retweet
				on Tweet.type = 3 and Tweet.parent_id = Retweet.id
				left join users as ParentUser
				on Tweet.type = 3 and Retweet.user_id = ParentUser.id
				left join tweets as RTByme
				on RTByme.type =3 and RTByme.user_id = $userId and RTByme.parent_id =Tweet.id
				order by Tweet.id DESC
				Limit $page,$count";
				//debug($tweetId);
				//$this->Tweet->unbindModel(array('hasMany'=>array('Timeline','Mention','Favorite'),'hasOne'=>array('Place')));
				$favoriteList =$this->Favorite->getDataSource()->query($query);
					
				//debug($favoriteList);
				//debug($listparent);
				$response = array("status_code" => 0,"message" =>'0k',"entity" =>$favoriteList);
			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>'');
			}
			
			//debug($response);
			echo json_encode($response);
		}
	}
}